package com.thh.service;

import com.thh.dao.OrderDataBaseDao;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @Author thh
 * @Description
 * @Version 1.0
 **/
@Service
public class OrderService {

    @Autowired
    OrderDataBaseDao orderDataBaseDao;


    @Autowired
    MQService mqService;

    // 创建订单 springboot
    @Transactional(rollbackFor = Exception.class) //+ datasource
    public void createOrder(JSONObject orderInfo) throws  Exception{
        // 1 : 订单信息 - 插入订单系统 订单数据 （事务-1）
        orderDataBaseDao.saveOrder(orderInfo);

        // 2 : 通过http接口发送订单消息到远单系统 read time out
        String result = callDispatchHttpApi(orderInfo); //TimeoutException
        if(!"ok".equalsIgnoreCase(result)){
            throw  new Exception("创建订单失败，原因：【运单接口调用失败!】");
        }
    }


    /*
     * @Author thh
     * @Description 通过http请求发送运单系统中，将订单号传过去
     * @Date 15:13 2020/4/29
     * @Param [orderInfo]
     * @return java.lang.String
     **/
    private String callDispatchHttpApi(JSONObject orderInfo) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //设置超时时间> 3秒
        requestFactory.setConnectTimeout(3000);
        //处理超时时间 > 2秒
        requestFactory.setReadTimeout(2000);

        // 创建远程访问对象
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String httpurl = "http://127.0.0.1:8082/dispatch-api/diapatch?orderId="+orderInfo.getString("orderId");
        String result = restTemplate.getForObject(httpurl,String.class);
        return result;
    }



}
